import React, { useEffect, useState } from "react";
import styled from "styled-components";
import axios from "axios";
import { Buffer } from "buffer";
import loader from "../assets/loader.gif";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { useNavigate } from "react-router-dom";
import { setAvatarRoute } from "../utils/APIRoutes";

export default function SetAvatar() {
  const demoAvatars = [
    'Clementine',
    'Morty',
    'Rodion Raskolnikov',
    'Sam Solo',
    'Starcrasher',
    'Shack',
    'Desmond',
    'Snake Harrison',
    'Pandemonium',
    'Broomhilda',
    'Cosmo Blue',
    'Blue Meal Shake',
    'Cryptonaut',
    'Maggot',
    'Matrix',
    'Hiro',
    'Mavericat',
    'Huxley',
    'Elton David-Black',
    'Katerina Zoo',
    'Bloomdalf',
    'Emma',
    'The Elephant\'s Cat',
    'Nigel Ziemssen',
    'Sir Henchard',
    'Philip Klaus',
    'Daniel Marlowe',
    'Joachim Molesworth',
    'Molly Deronda',
    'Protagonist',
    'Lancelot',
    'Pechorin Bloom',
    'Kim',
    'Kim Patel',
    'Lorelei',
    'Battle Wooster',
    'Horatius',
    'Rhett James',
    'Moby Dick',
    'James Bolling',
    'Binx Bond',
    'Patrick Gatsby',
    'Inigo Argo',
    'Jay Bateman',
    'Victor Montoya',
    'Angela Flagg',
    'Randall Zone',
    'Major Salt',
    'Milo Minderbender',
    'Major Machine',
    'Skeleto',
    'Heep Starr',
    '11th Monster',
    'Wunderlick',
    'Big Brother',
    'Gonlithli',
    'Ebenezer Dimmsdale',
    'Hester Vega',
    'Honey Bunny',
    'Vincent Plant',
    'Butch Wallace',
    'Marsellus Coolidge',
    'Tuco',
    'Angel Boy',
    'Pablo Grimes',
    'Bounty Hunter',
    'Agent Smith',
    'Oracle',
    'Apoc State',
    'Switch',
    'Choi',
    'Angel Eyes',
    'Spoon Eyes',
    'Papillon',
    'Snooze 11',
    'Projectionist',
    'Landlady',
    'Ned Ramirez',
    'Pablo Shimada',
    'Sonny Zen',
    'Bruno Fox',
    'Joker',
    'Lucius Tattaglia',
    'Scareblow',
    'Sugar Crash',
    'Neurostatic',
    'Kambei Corleone',
    'Shichiroji Karatoza',
    'Kuninori Bun Lord',
    'Bun Pusher',
    'Etno',
    'Wiggly Corleone',
    'Magnetofon',
    'Hitpagadee',
    'Doge',
    'Doge Panda',
    'Doge Locamotiv',
    'Doge Bulls',
    'Doge Lavrinovich',
    'Dogecoin',
    'Ethereum',
    'BTC',
    'Cardano',
    'ETH',
    'Weeberblitz',
    'Arkadion',
    'Ninesouls',
    'Psycat',
    'Indoqueen',
    'DoubleDanceDragon',
    'Kinestetic Moves',
    'Zen Flash',
    'Orbit Escape',
    'Sin Azucar',
    'Particle Machine',
    'Spanglinga',
    'Pandalion',
    'Music Razor',
    'Bugzilla',
    'Bugz Bunuel',
    'Satoshi',
    'Nakamoto',
    'МЦ ДРУИД',
    'Jekaterina',
    'Quito',
    'Ouarzazate',
    'Bogota',
    'Essaouira',
    'Extremadura',
    'Guadalajara',
    'Aphex',
    'Squarepusher',
    'Orbital',
    'Copycat',
    'Mozart',
    'Tesla',
    'Linux',
    'Ki',
    'Aphex Maiden',
    'Iron Twin',
  ];
  const api = `https://api.multiavatar.com/`;
  const navigate = useNavigate();
  const [avatars, setAvatars] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedAvatar, setSelectedAvatar] = useState(undefined);
  const toastOptions = {
    position: "bottom-right",
    autoClose: 8000,
    pauseOnHover: true,
    draggable: true,
    theme: "dark",
  };

  useEffect(async () => {
    if (!localStorage.getItem(process.env.REACT_APP_LOCALHOST_KEY))
      navigate("/login");
  }, []);

  const setProfilePicture = async () => {
    if (selectedAvatar === undefined) {
      toast.error("Please select an avatar", toastOptions);
    } else {
      const user = await JSON.parse(
        localStorage.getItem(process.env.REACT_APP_LOCALHOST_KEY)
      );

      const { data } = await axios.post(`${setAvatarRoute}/${user._id}`, {
        image: avatars[selectedAvatar],
      });

      if (data.isSet) {
        user.isAvatarImageSet = true;
        user.avatarImage = data.image;
        localStorage.setItem(
          process.env.REACT_APP_LOCALHOST_KEY,
          JSON.stringify(user)
        );
        navigate("/");
      } else {
        toast.error("Error setting avatar. Please try again.", toastOptions);
      }
    }
  };

  useEffect(async () => {
    const data = [];
    for (let i = 0; i < 4; i++) {
      // await fetch(
      //   `${api}`
      // ).then(res => res.text())
      // .then(svg => {
      //   console.log(svg)
      //   const buffer = new Buffer(svg);
      //   data.push(buffer.toString("base64"));
      // });
      await fetch(`${api}`+JSON.stringify(`${demoAvatars[Math.floor(Math.random() * (demoAvatars.length + 1))]}.svg`)).then(res => {
        res.text().then(svg =>{
          // console.log(svg)
          data.push(svg);
        })
      });
    }
    setAvatars(data);
    setIsLoading(false);
  }, []);
  return (
    <>
      {isLoading ? (
        <Container>
          <img src={loader} alt="loader" className="loader" />
        </Container>
      ) : (
        <Container>
          <div className="title-container">
            <h1>Pick an Avatar as your profile picture</h1>
          </div>
          <div className="avatars">
            {avatars.map((avatar, index) => {
              console.log(avatar)
              // const htmlString = avatar;
              // const htmlTags = htmlString.match(/<[^>]*>/g);
              // const reactElements = htmlTags.map((tag) => {
              //   const tagName = tag.match(/<(w+)/)[1];
              //   const props = {};
              //   const attributes = tag.match(/w+="[^"]*"/g) || [];
              //   attributes.forEach((attribute) => {
              //     const [key, value] = attribute.split('=');
              //     props[key] = value.replace(/"/g, '');
              //   });
              //   return React.createElement(tagName, props, []);
              // });
              return (
                <div
                  className={`avatar ${
                    selectedAvatar === index ? "selected" : ""
                  }`}
                >
                  <div
                    alt="avatar"
                    key={index}
                    onClick={() => setSelectedAvatar(index)}
                    className="avatar"
                    dangerouslySetInnerHTML={{__html:avatar}}
                  ></div>
                </div>
              );
            })}
          </div>
          <button onClick={setProfilePicture} className="submit-btn">
            Set as Profile Picture
          </button>
          <ToastContainer />
        </Container>
      )}
    </>
  );
}

const Container = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 3rem;
  background-color: #131324;
  height: 100vh;
  width: 100vw;

  .loader {
    max-inline-size: 100%;
  }

  .title-container {
    h1 {
      color: white;
    }
  }
  .avatars {
    display: flex;
    gap: 2rem;

    .avatar {
      border: 0.4rem solid transparent;
      padding: 0.4rem;
      border-radius: 5rem;
      display: flex;
      justify-content: center;
      align-items: center;
      transition: 0.5s ease-in-out;
      svg {
        height: 6rem;
        transition: 0.5s ease-in-out;
      }
    }
    .selected {
      border: 0.4rem solid #4e0eff;
    }
  }
  .submit-btn {
    background-color: #4e0eff;
    color: white;
    padding: 1rem 2rem;
    border: none;
    font-weight: bold;
    cursor: pointer;
    border-radius: 0.4rem;
    font-size: 1rem;
    text-transform: uppercase;
    &:hover {
      background-color: #4e0eff;
    }
  }
`;
